## Tree based methods analysis of voting data

## CART
tree <- rpart(vote~., data=cbind("vote"=dep$vote18, df), method="class")
#rpart.plot(tree)  # un-pruned tree

pruned <- prune(tree, cp=tree$cptable[which.min(tree$cptable[,"xerror"]),"CP"])

png("figures/vote_tree.png", width = 7, height = 7, units = 'in', res = 300)
rpart.plot(pruned, fallen.leaves = F, tweak=1.4)
dev.off()

# chosen to give comparable sparsity to BRS
png("figures/vote_tree_sparse.png", width = 6, height = 6, units = 'in', res = 300)
rpart.plot(prune(tree, cp=tree$cptable[3, 1]), fallen.leaves = F)
dev.off()



## RF
set.seed(123)
forest <- randomForest(vote~., data=cbind("vote"=as.factor(dep$vote18), df))
png("figures/vote_rf.png", width = 6, height = 4, units = 'in', res = 300)
varImpPlot(forest, main=NULL)
dev.off()

    


